package re56;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import re56.equipment.EvolvedNodeB;
import re56.equipment.UserEquipment;
import re56.layer.RadioLayer;
import re56.packet.PUSCHPacket;


// this class is just a helper.
public class LTEHelper extends Thread
{
	private EvolvedNodeB eNB;
	private List<UserEquipment> UEs = new ArrayList<UserEquipment>();
	
	
	// TODO: un couple seul de Radio Layer ??
	private RadioLayer radioLayerDL;
	private RadioLayer radioLayerUL;
	
	
	private boolean done;
	
	private Random rand = new Random();
	
	
	public LTEHelper()
	{
		done = false;
	}
	
	
	public EvolvedNodeB createENB()
	{
		eNB = new EvolvedNodeB(radioLayerDL, radioLayerUL);
		return eNB;
	}
	
	
	public UserEquipment createUE()
	{
		UserEquipment ue = new UserEquipment(radioLayerDL, radioLayerUL);
		UEs.add(ue);
		return ue;
	}
	
	
	public void destroyUE()
	{
		if(UEs.size() == 0)
			return;
		
		UserEquipment ue0 = UEs.get(0);
		
		eNB.disconnectUE(ue0);
		
		UEs.remove(ue0);
	}
	
	
	public void startSimulation()
	{
		start();
	}
	
	
	public void stopSimulation()
	{
		done = true;
	}
	
	
	public void useFrequencies(int uplink_freq, int downlink_freq, int bandwidth)
	{
		radioLayerDL = new RadioLayer(downlink_freq, bandwidth, RadioLayer.DL_MODE);
		radioLayerUL = new RadioLayer(uplink_freq, bandwidth, RadioLayer.UL_MODE);
	}
	
	
	public void run()
	{
		System.out.println("Simulation Started with "+UEs.size()+" User Equipments");
		
		//radioLayerDL.start();
		//radioLayerUL.start();
		
		int id_message = 0;
		
		while(!done)
		{
			// for each UE. Do something.
			Iterator<UserEquipment> it = UEs.iterator();
			while(it.hasNext())
			{
				UserEquipment ue = it.next();
				
				// if already connected,
				// create trafic
				if(ue.isConnected())
				{
					// 40% of chance to create trafic
					if(rand.nextInt(100) < 20)
					{
						PUSCHPacket p = new PUSCHPacket();
						
						String message = "("+id_message+") Hello";
						id_message++;
						
						p.setData(message.getBytes());
						
						ue.send(p, eNB);
					}
				}
				else
				{
					// this ue is still not connected.
					eNB.connectUE(ue);
				}
			}
			
			
			// 20% of chance to create a new UE.
			if(rand.nextInt(100) < 20)
			{
				System.out.println("+ One new UE has been added.");
				createUE();
			}
			
			// 5% of chance to destroy an UE.
			if(rand.nextInt(100) < 5)
			{
				System.out.println("- One UE has quit.");
				destroyUE();
			}
			
			
			try
			{
				Thread.sleep(2000);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}
